package org.bobo.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class Upload {

    // 定义一个目标路径，就是我们要把图片上传的位置
    @Value(value = "${bobo.path.upload}")
    private String basepath;

    // 定义访问图片路径
    @Value(value = "${bobo.path.filePath}")
    private String SERVER_PATH;


    public String uploadImg(MultipartFile file) {
        String contentType = file.getContentType();
        // 获取上传图片的名称
        String filename = file.getOriginalFilename();
        // 为了保证图片在服务器中名字的唯一性，使用UUID来对filename进行改写
        String uuid = UUID.randomUUID().toString().replace("-", "");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());
        // 将生成的uuid和filename惊醒拼接
        String newFileName = "img" + File.separator + date + File.separator + uuid + '-' + filename;
        // 创建一个文件实例对象
        File image = new File(basepath, newFileName);

        if (!image.exists()) {
            image.mkdirs();
        }
        // 对这个文件进行上传操作
        try {
            file.transferTo(image);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(SERVER_PATH);

        return SERVER_PATH + newFileName.replace("\\", "/");
    }

    public String uploadVideoToM3U8(MultipartFile file) {
        String contentType = file.getContentType();
        // 获取上传图片的名称
        String filename = file.getOriginalFilename();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());

        // 为了保证图片在服务器中名字的唯一性，使用UUID来对filename进行改写
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 将生成的uuid和filename惊醒拼接
        String newFileName = "video" + File.separator + date + File.separator + uuid + File.separator + filename;
        // 创建一个文件实例对象
        File video = new File(basepath, newFileName);

        if (!video.exists()) {
            video.mkdirs();
        }
        // 对这个文件进行上传操作
        try {
            file.transferTo(video);
        } catch (IOException e) {
            e.printStackTrace();
        }
        File m3u8 = new File(basepath + File.separator + newFileName.substring(0, newFileName.lastIndexOf(".")) + ".m3u8");
        try {
            m3u8.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //m3u8分片编码
        // 使用FFmpeg将视频分成多个小块

        //被注释的这个快一点
        //ProcessBuilder pb = new ProcessBuilder("ffmpeg", "-i", video.getPath(), "-codec", "copy", "-start_number", "0", "-hls_time", "1", "-hls_list_size", "0", "-f", "hls", m3u8.getPath());
        ProcessBuilder pb = new ProcessBuilder("ffmpeg", "-i", video.getPath(), "-force_key_frames", "expr:gte(t,n_forced*1)", "-strict", "-2", "-c:a", "aac","-c:v", "libx264", "-hls_time", "1", "-hls_list_size", "0", "-f", "hls", m3u8.getPath());
        // 将标准错误流和标准输出流合并
        pb.redirectErrorStream(true);

        Process p = null;
        try {
            p = pb.start();

            // 处理FFmpeg的输出信息
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            p.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String tempUrl = SERVER_PATH + newFileName.replace("\\", "/");
        return tempUrl.substring(0, tempUrl.lastIndexOf(".")) + ".m3u8";
    }
//        InputStream inputStream = p.getInputStream();
//        InputStream errorStream = p.getErrorStream();
//        InputStream combinedStream = new SequenceInputStream(inputStream, errorStream);
//        BufferedReader reader = new BufferedReader(new InputStreamReader(combinedStream));
//        String line;
//
//        try {
//            while ((line = reader.readLine()) != null) {
//                System.out.println(line);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

}
